package com.mumulx.check.web.controller;

import com.aliyuncs.utils.StringUtils;
import com.mumulx.check.model.SubmitFileRecord;
import com.mumulx.check.redis.util.FastDfsClientUtil;
import com.mumulx.check.service.service.SubmitFileRecordService;
import com.mumulx.check.service.util.RespBean;
import com.mumulx.check.service.util.exception.CustomException;
import com.mumulx.check.service.util.exception.CustomExceptionType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/4/28
 *  Time: 22:48
 */
@Controller
@RequestMapping("/submitFileRecord")
public class SubmitFileRecordController {


    @Resource
    SubmitFileRecordService submitFileRecordService;
    @Resource
    FastDfsClientUtil fastDfsClientUtil;

    @GetMapping("/downloadZip")
    @ResponseBody
    public void downloadZip(@RequestParam(value = "srId") String srId,HttpServletResponse response) {

        //Object userId = session.getAttribute("user_id");
        /*if (userId == null) {
            String message = "您还没有登录，请先登录！";
            return RespBean.error(message);
        }*/
        //int user_id = (int) userId;
        if (StringUtils.isEmpty(srId)) {
            String message = "请选择要下载的测试记录！";
            //return RespBean.error(message);
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR);
        }

        try {
            String zipName = UUID.randomUUID().toString()+".zip";
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipName.getBytes("GB2312"), "ISO-8859-1"));  // 需要编码否则中文乱码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/zip;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        //获取测试文件记录集合
        List<SubmitFileRecord> submitFileRecords = submitFileRecordService.queryFileRecordsBysrid(Integer.valueOf(srId));

        //SubmitRecord submitRecord = submitRecordService.queryRecordBySrId(Integer.valueOf(srId));
        //创建压缩文件 将文件直接以流的方式相应给前端
        try {
            ZipOutputStream zipOutputStream= new ZipOutputStream(response.getOutputStream());
            String sfrXslFile = submitFileRecords.get(0).getSfrXslFile();
            ZipEntry zipEntryXsl = new ZipEntry("checkmate_log.xsl");

            zipOutputStream.putNextEntry(zipEntryXsl);
            zipOutputStream.write(fastDfsClientUtil.download_bytes(sfrXslFile));


            fastDfsClientUtil.download_bytes(sfrXslFile);

            submitFileRecords.forEach(submitFileRecord -> {
                String substring = submitFileRecord.getSfrFileName().substring(0, submitFileRecord.getSfrFileName().lastIndexOf("."));

                ZipEntry zipEntryPng = new ZipEntry(substring + ".png");
                ZipEntry zipEntryPrt = new ZipEntry(substring + ".prt");
                ZipEntry zipEntryXml = new ZipEntry(substring + ".xml");
                //将每个文件添加到压缩文件
                try {
                    zipOutputStream.putNextEntry(zipEntryPng);
                    zipOutputStream.write(fastDfsClientUtil.download_bytes(submitFileRecord.getSfrPngFile()));

                    zipOutputStream.putNextEntry(zipEntryPrt);
                    zipOutputStream.write(fastDfsClientUtil.download_bytes(submitFileRecord.getSfrFilePath()));

                    zipOutputStream.putNextEntry(zipEntryXml);
                    zipOutputStream.write(fastDfsClientUtil.download_bytes(submitFileRecord.getSfrXmlFile()));

                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //return RespBean.ok("下载准备完成");
    }


    /**
     *将文件写出到流 【方法名】{方法的功能/动作描述}
     */
   /* private void writeOut(HttpServletResponse response, File zipFile) throws IOException {
        response.reset();
        response.setContentType("application/zip");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFile.getName());
        OutputStream outputStream = response.getOutputStream();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(zipFile.getPath());
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } finally {
            if (null != fis) {
                fis.close();
            }
            if (null != outputStream) {
                outputStream.close();
            }
        }
    }*/


}
